package co.kr.bettersoft.carrotmerchantmobile.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import co.kr.bettersoft.carrotmerchantmobile.activity.R;
import co.kr.bettersoft.carrotmerchantmobile.domain.CheckMileageMerchant;
import co.kr.bettersoft.carrotmerchantmobile.domain.CheckMileageMileage;

import android.content.Context;
import android.util.Log;

public class CarrotMerchantMobileRest {
	String TAG = "CarrotMerchantMobileRest";

	// 서버 통신
	int responseCode = 0;
	String controllerName ="";
	String methodName ="";
	String serverName = CommonConstant.serverName;
	URL postUrl2 = null;
	HttpURLConnection connection2 = null;
	int isRunning = 0;		// 통신 도중 중복 호출을 방지하기 위함.
	String fullUrl = "";
	String inputJson = "";
	JSONObject jsonObject;
	JSONObject jsonObj;
	JSONArray jsonArray2;
	JSONObject obj = new JSONObject();

	String nowTime = "";	// 현시각

	// 결과
	String callResult = "";
	String tempstr = "";
	int max;
	
	// 가맹점 정보 저장
	CheckMileageMerchant checkMileageMerchant = new CheckMileageMerchant(); 
	// 마일리지 정보 저장
	CheckMileageMileage checkMileageMileage = new CheckMileageMileage(); 
	// 마일리지 리스트
	public ArrayList<CheckMileageMileage> checkMileageMileageEntries1 = new ArrayList<CheckMileageMileage>();	// 1차적으로 조회한 결과. 
	List<CheckMileageMileage> checkMileageMileageEntriesFn = new ArrayList<CheckMileageMileage>();				// 최종 산출물
	
	public Context recievedContext;
	
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	// 서버 통신

	/**
	 * RestLogin
	 *   로그인한다
	 * @param checkMileageMerchantParam 
	 * @return  String
	 */
	public String RestLogin(CheckMileageMerchant checkMileageMerchantParam ){

		checkMileageMerchant = checkMileageMerchantParam;

		nowTime = CommonUtils.getNowDate();
		// 파라미터 셋팅
		controllerName = "checkMileageMerchantController";
		methodName = "login";
		fullUrl = serverName+"/"+controllerName+"/"+methodName;
		obj = new JSONObject();
		try{		 
			obj.put("merchantId", checkMileageMerchant.getMerchantId());		// 아디
			obj.put("password", checkMileageMerchant.getPassword());			// 비번
			obj.put("activateYn", "Y");				// 활성화 여부
		}catch(Exception e){
			e.printStackTrace();
		}
		inputJson = "{\"checkMileageMerchant\":" + obj.toString() + "}";

		// 서버호출 메소드 실행
		callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(callResult.equals("S")){
		}
		return callResult;
	}

	
	/**
	 * RestSelectMerchantInformation
	 *   가맹점 정보 가져온다
	 * @return  String
	 */
	public String RestSelectMerchantInformation(CheckMileageMerchant checkMileageMerchantParam ){

		checkMileageMerchant = checkMileageMerchantParam;

		nowTime = CommonUtils.getNowDate();
		// 파라미터 셋팅
		controllerName = "checkMileageMerchantController";
		methodName = "selectMerchantInformation";
		fullUrl = serverName+"/"+controllerName+"/"+methodName;
		obj = new JSONObject();
		try{		 
			obj.put("merchantId", checkMileageMerchant.getMerchantId());		// 아디
			obj.put("activateYn", "Y");
		}catch(Exception e){
			e.printStackTrace();
		}
		inputJson = "{\"checkMileageMerchant\":" + obj.toString() + "}";

		// 서버호출 메소드 실행
		callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(callResult.equals("S")){
		}
		return callResult;
	}
	
	
	/**
	 * RestCheckMileageExist
	 *     고객 정보를 가져온다.
	 * @return  String
	 */
	public String RestCheckMileageExist(CheckMileageMileage checkMileageMileageParam ){

		checkMileageMileage = checkMileageMileageParam;

		nowTime = CommonUtils.getNowDate();
		// 파라미터 셋팅
		controllerName = "checkMileageMileageController";
		methodName = "checkMileageExist";
		fullUrl = serverName+"/"+controllerName+"/"+methodName;
		obj = new JSONObject();
		try{		 
			obj.put("checkMileageMembersCheckMileageId", checkMileageMileage.getCustomerId());
			obj.put("checkMileageMerchantsMerchantId", checkMileageMileage.getMerchantId());
			obj.put("activateYn", "Y");
		}catch(Exception e){
			e.printStackTrace();
		}
		inputJson = "{\"checkMileageMileage\":" + obj.toString() + "}";

		// 서버호출 메소드 실행
		callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(callResult.equals("S")){
		}
		return callResult;
	}


	/**
	 * RestRegisterMileage
	 *   마일리지를 적립한다.
	 * @return  String
	 */
	public String RestRegisterMileage(CheckMileageMileage checkMileageMileageParam ){

		checkMileageMileage = checkMileageMileageParam;

		nowTime = CommonUtils.getNowDate();
		// 파라미터 셋팅
		controllerName = "checkMileageMileageController";
		methodName = "registerMileage";
		fullUrl = serverName+"/"+controllerName+"/"+methodName;
		obj = new JSONObject();
		try{		 
			obj.put("checkMileageMembersCheckMileageId", checkMileageMileage.getCustomerId());
			obj.put("checkMileageMerchantsMerchantId", checkMileageMileage.getMerchantId());
			obj.put("modifyDate", nowTime);		// 수정일 : 현재 시각
			obj.put("registerDate", nowTime);	// 등록일 : 현재 시각
			obj.put("mileage", checkMileageMileage.getMileage());			// 마일리지: 기존 마일리지
			obj.put("bill", checkMileageMileage.getBill());					// 금액 : 결재 금액
			obj.put("content", "AMASS");					// 내용 : AMASS		   적립 또는 신규.
			obj.put("activateYn", "Y");
		}catch(Exception e){
			e.printStackTrace();
		}
		inputJson = "{\"checkMileageMileage\":" + obj.toString() + "}";

		// 서버호출 메소드 실행
		callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(callResult.equals("S")){
			try{
				jsonObject = new JSONObject(tempstr);
				JSONObject jsonobj2 = jsonObject.getJSONObject("checkMileageMileage");
				callResult = jsonobj2.getString("result"); 
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return callResult;
	}

	/**
	 * RestRegisterCashMileage
	 *   현금 마일리지를  적립한다.
	 * @return  String
	 */
	public String RestRegisterCashMileage(CheckMileageMileage checkMileageMileageParam ){

		checkMileageMileage = checkMileageMileageParam;

		nowTime = CommonUtils.getNowDate();
		// 파라미터 셋팅
		controllerName = "checkMileageMileageController";
		methodName = "registerMileageCash";
		fullUrl = serverName+"/"+controllerName+"/"+methodName;
		obj = new JSONObject();
		try{		 
			obj.put("checkMileageMembersCheckMileageId", checkMileageMileage.getCustomerId());
			obj.put("checkMileageMerchantsMerchantId", checkMileageMileage.getMerchantId());
			obj.put("modifyDate", nowTime);		// 수정일 : 현재 시각
			obj.put("registerDate", nowTime);	// 등록일 : 현재 시각
			obj.put("mileage", checkMileageMileage.getMileage());			// 마일리지: 기존 마일리지
			obj.put("bill", checkMileageMileage.getBill());					// 금액 : 결재 금액
			obj.put("content", "AMASS");					// 내용 : AMASS		   적립 또는 신규.
			obj.put("activateYn", "Y");
		}catch(Exception e){
			e.printStackTrace();
		}
		inputJson = "{\"checkMileageMileage\":" + obj.toString() + "}";

		// 서버호출 메소드 실행
		callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(callResult.equals("S")){
			try{
				jsonObject = new JSONObject(tempstr);
				JSONObject jsonobj2 = jsonObject.getJSONObject("checkMileageMileage");
				callResult = jsonobj2.getString("result"); 
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return callResult;
	}


	/**
	 * RestUpdateMileage
	 *    마일리지를 사용한다.
	 * @return  String
	 */
	public String RestUpdateMileage(CheckMileageMileage checkMileageMileageParam ){

		checkMileageMileage = checkMileageMileageParam;

		nowTime = CommonUtils.getNowDate();
		// 파라미터 셋팅
		controllerName = "checkMileageMileageController";
		methodName = "updateMileage";
		fullUrl = serverName+"/"+controllerName+"/"+methodName;
		obj = new JSONObject();
		try{		 
			obj.put("checkMileageMembersCheckMileageId", checkMileageMileage.getCustomerId());
			obj.put("checkMileageMerchantsMerchantId", checkMileageMileage.getMerchantId());
			obj.put("modifyDate", nowTime);		// 수정일 : 현재 시각
			obj.put("registerDate", nowTime);	// 등록일 : 현재 시각
			obj.put("mileage", checkMileageMileage.getMileage());			// 마일리지: 기존 마일리지
			obj.put("spendMileage", checkMileageMileage.getBill());					// 금액 : 결재 금액
			obj.put("content", "CHECK");					// 내용 : AMASS		   적립 또는 신규.
			obj.put("activateYn", "Y");
		}catch(Exception e){
			e.printStackTrace();
		}
		inputJson = "{\"checkMileageMileage\":" + obj.toString() + "}";

		// 서버호출 메소드 실행
		callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(callResult.equals("S")){
			try{
				jsonObject = new JSONObject(tempstr);
				JSONObject jsonobj2 = jsonObject.getJSONObject("checkMileageMileage");
				callResult = jsonobj2.getString("result"); 
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return callResult;
	}


	/**
	 * RestSelectMerchantMemberMileageList
	 *    고객 마일리지 리스트를 가져온다.
	 * @param contextParam 
	 * @return  String
	 */
	public String RestSelectMerchantMemberMileageList(CheckMileageMileage checkMileageMileageParam, Context contextParam ){

		checkMileageMileage = checkMileageMileageParam;
		recievedContext = contextParam;
		
		nowTime = CommonUtils.getNowDate();
		// 파라미터 셋팅
		controllerName = "checkMileageMileageController";
		methodName = "selectMerchantMemberMileageList";
		fullUrl = serverName+"/"+controllerName+"/"+methodName;
		obj = new JSONObject();
		try{		 
			obj.put("checkMileageMerchantsMerchantId", checkMileageMileage.getMerchantId());		// 전달받은 가맹점 아이디 그대로 사용
			obj.put("activateYn", "Y");
		}catch(Exception e){
			e.printStackTrace();
		}
		inputJson = "{\"checkMileageMileage\":" + obj.toString() + "}";

		// 서버호출 메소드 실행
		callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(callResult.equals("S")){
			try {
				jsonArray2 = new JSONArray(tempstr);
				max = jsonArray2.length();
			} catch (JSONException e1) {
				e1.printStackTrace();
				callResult = "F";
			}
			if(max>0){
				checkMileageMileageEntries1 = new ArrayList<CheckMileageMileage>(max);		
				for ( int i = 0; i < max; i++ ){
					JSONObject jsonObj;
					try {
						jsonObj = jsonArray2.getJSONObject(i).getJSONObject("checkMileageMileage");	// 대소문자 주의
						String tempCustomerId="";
						String tempCustomerMileage="";
						String tempCustomerUpdateDate="";
						String tempCustomerRegisterDate="";
						String tempCustomerPhoneNumber="";
						try{
							tempCustomerId = jsonObj.getString("checkMileageMembersCheckMileageId");
						}catch(Exception e1){ tempCustomerId = ""; }
						try{
							tempCustomerMileage = jsonObj.getString("mileage");
						}catch(Exception e1){ tempCustomerMileage = ""; }
						try{
							tempCustomerUpdateDate = jsonObj.getString("modifyDate");
							
							String tmpstr2 = "";
							if(tempCustomerUpdateDate.length()>9){
								tmpstr2 = tempCustomerUpdateDate.substring(0, 4)+ recievedContext.getString(R.string.year) 		// 년
								+ tempCustomerUpdateDate.substring(5, 7)+ recievedContext.getString(R.string.month) 					// 월
								+ tempCustomerUpdateDate.substring(8, 10)+ recievedContext.getString(R.string.day) 					// 일
								;
								tempCustomerUpdateDate = tmpstr2;
							}
						}catch(Exception e1){ tempCustomerUpdateDate = ""; }
						try{
							tempCustomerRegisterDate = jsonObj.getString("registerDate");
							if(tempCustomerRegisterDate!=null &&(tempCustomerRegisterDate.length()>16)){
								tempCustomerRegisterDate = tempCustomerRegisterDate.substring(0, 16);
							}
						}catch(Exception e1){ tempCustomerRegisterDate = ""; }
						try{
							tempCustomerPhoneNumber = jsonObj.getString("phoneNumber");
						}catch(Exception e1){ tempCustomerPhoneNumber = ""; }

						checkMileageMileageEntries1.add(
								new CheckMileageMileage(
										tempCustomerId,
										tempCustomerMileage,
										tempCustomerUpdateDate,		
										tempCustomerRegisterDate,
										tempCustomerPhoneNumber
								)
						);
					} catch (Exception e) {
						e.printStackTrace();
						callResult = "F";
					}	
				}
				checkMileageMileageEntriesFn = checkMileageMileageEntries1;
			}
		}
		return callResult;
	}
	


	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// 공용 서버 호출 메소드
	public String callServerMethod(String fullUrl, String inputJson){
		try{
			postUrl2 = new URL(fullUrl);
			connection2 = (HttpURLConnection) postUrl2.openConnection();
			connection2.setConnectTimeout(CommonConstant.serverConnectTimeOut);
			connection2.setDoOutput(true);
			connection2.setInstanceFollowRedirects(false);
			connection2.setRequestMethod("POST");
			connection2.setRequestProperty("Content-Type", "application/json");
			Thread.sleep(200);
			OutputStream os2 = connection2.getOutputStream();
			os2.write(inputJson.getBytes("UTF-8"));
			os2.flush();
			responseCode = connection2.getResponseCode();
			InputStream in =  connection2.getInputStream();
			if(responseCode==200 || responseCode==204){
				// 결과를 처리.
				BufferedReader reader = new BufferedReader(new InputStreamReader(in), 8192);
				StringBuilder builder = new StringBuilder();
				String line =null;
				try {
					while((line=reader.readLine())!=null){
						builder.append(line).append("\n");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				tempstr = builder.toString();
				callResult = "S";
			}else{
				Log.d(TAG,"Fail["+responseCode+"]");
				callResult="";
			}
		}catch(Exception e){ 
			e.printStackTrace();
			callResult="";
			initNetwork();
		}
		isRunning = 0;
		return callResult;
	}


	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////		
	// 처리 결과 반환 메소드
	
	// 고객 마일리지 리스트
	public List<CheckMileageMileage> getCheckMileageMileageEntriesFn(){
		return checkMileageMileageEntriesFn;
	}

	
	// tempstr
	public String getTempstr(){
		return tempstr;
	}

	/////////////////////////////////////////////////////////////////////////////////////////////////////
	//유틸

	// 넷웍 초기화
	public void initNetwork(){
		if(connection2!=null){
			connection2.disconnect();
			connection2 = null;
		}
		postUrl2 = null;
	}
	
}
